package com.pet.server.ext.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.codehaus.jackson.annotate.JsonValue;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;

import com.baidu.gson.JsonObject;
import com.pet.server.ext.BeanToJson;
import com.pet.server.ext.Config;
import com.pet.server.ext.constants.BaseAttribute;
import com.pet.server.ext.constants.Status.Source;
import com.pet.server.ext.data.Article;
import com.pet.server.ext.data.Image;
import com.pet.server.ext.data.PetAdopt;
import com.pet.server.ext.data.PetMissing;
import com.pet.server.ext.data.ProductInfo;
import com.pet.server.ext.util.cache.ConstantUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonUtil {
	
    private static String fillStringByArgs(String str,String[] arr){
        Matcher m=Pattern.compile("\\{(\\d)\\}").matcher(str);
        while(m.find()){
            str=str.replace(m.group(),arr[Integer.parseInt(m.group(1))]);
        }
        return str;
    }
	
    
    public static JSONArray parseBaseJsonArray(List<ProductInfo> list){
    	JSONArray array = new JSONArray();
    	for(ProductInfo p:list){
			JSONObject po = new JSONObject();
			po.put("ico_path", p.ico_path);
			po.put("id", p.id);
			po.put("pet_cate", p.pet_cate);
			po.put("product_cate", p.product_cate);
			po.put("product_href", p.product_href);
			po.put("product_name", p.product_name);
			po.put("product_description", p.product_description);
			po.put("product_price", p.product_price);
			po.put("sale_price", p.sale_price);
			if(!StringUtil.isEmpty(p.images)&&!"null".equals(p.images)){
				//po.put("images", p.images);
			}
			po.put("source", Source.tmall.toString());
			po.put("num_iid", p.num_iid);
			array.add(po);
		}
    	return array;
    }
    
    
	public static void main(String[] args){
		//String url = "http://re.m.jd.com/cps/item/10114364653.html?wareId=10114364653&cu=true&utm_source=kong&utm_medium=tuiguang&utm_campaign=t_326418498_&utm_term=60ea625fb57449a4943d005f7e5e625d";
		String url = "http://item.m.jd.com/product/1000055710.html";
		JSONObject o = urlToJson(url,"jd");
	    System.out.println(o.toString());
	}
	public static Map<String, String> parseParam(String url){
		Map<String, String> map = new HashMap<String, String>();
		if(!StringUtil.isEmpty(url)){
			String[] strs=url.split("\\?");
			String uri=strs[0];
			int i = uri.lastIndexOf("/");
			if ((i > -1) && (i < (uri.length() - 1))) {
				String ids=uri.substring(i + 1).split("\\.")[0];
				map.put("product_id", ids);
			}
			if(strs.length>1){
				
				String params = strs[1];
				String[] kvs = params.split("&");
				for(String entry:kvs){
					String[] kv=entry.split("=");
					if(kv.length>1){
						map.put(kv[0], kv[1]);
					}
				}
			}	
		}
		return map;
	}
	
	public static JSONArray  product2JsonArray(List<ProductInfo> list,String ...names){
		JSONArray r = new JSONArray();
		for(ProductInfo p:list){
			JSONObject o = BeanToJson.beanToJson(p,names);
			o.put("client",urlToJson(StringUtil.dealNull(p.client_url,p.product_href),p.source));
			r.add(o);
		}
		return r;
	}
	
	//    "jdv": "|kong|t_326418498_|tuiguang|60ea625fb57449a4943d005f7e5e625d",//以|分割，第一个空串，第二个是utm_source对应的值，第三个为utm_campaign参数，第四个为utm_term参数
	public static JSONObject urlToJson(String url,String source){
		Map<String, String> map = parseParam(url);
		String jdv="";
		String product_id="";
		if("jd".equals(source)){
			jdv = "|"+StringUtil.dealNull(map.get("utm_source"))+"|"+StringUtil.dealNull(map.get("utm_campaign"))+"|"+StringUtil.dealNull(map.get("utm_term"));
			product_id=StringUtil.dealNull(map.get("wareId"), map.get("product_id"));
		}else if("taobao".equals(source)){
			product_id=map.get("id");
		}
		JSONObject o = new JSONObject();
		o.put("category", "jump");
		o.put("des", "productDetail");
		o.put("skuId", product_id);
		o.put("sourceType", "unknown");
		o.put("sourceValue", "unknown");
		o.put("jda", "");
		o.put("mba_muid", "");
		o.put("mba_sid", "");
		o.put("jdv", jdv);
		
		o.put("unpl", "");
		o.put("mt_xid", "");
		o.put("mt_subsite", "");
		JSONObject se = new JSONObject();
		se.put("mt_subsite", "");
		se.put("__jdv", jdv);
		se.put("unpl", "");
		se.put("__jda", "");
		o.put("SE", se);
		return o;
	}
	
	public static JSONObject productDetail(List<Image> list,ProductInfo p,String...names){
		p.setProduct_description(StringUtil.dealNull(p.product_description));
		p.setProduct_detail(StringUtil.dealNull(p.product_detail));
		JSONObject o = BeanToJson.beanToJson(p,names);
		JSONArray r = new JSONArray();
		for(Image img:list){
			r.add(img.src);
		}
		o.put("product_detail", StringUtil.appendCss(Config.getValue("server.name"), p.product_detail));
		o.put("imgs", r);
		o.put("client",urlToJson(StringUtil.dealNull(p.client_url,p.product_href),p.source));
		return o;
	}
	
	public static JSONObject shareJson(String image_url,String title,String description,String url){
		JSONObject o = new JSONObject();
		o.put("image_url",image_url);
		o.put("title", title);
		o.put("description", description);
		o.put("url", url);
		return o;
		
	}
	public static  <T> T getValue(JSONObject json,String key,Class<T> type){
		if(json!=null&&json.containsKey(key)){
			return (T) json.get(key);
		}
		return null;
	}
	
	public static Long getTime(Date date){
		return null!=date?date.getTime():null;
	}
	public static JSONArray articleArray(List<Article> list){
		JSONArray array = new JSONArray();
		for(Article art:list){
			JSONObject o = new JSONObject();
			o.put("article_id", art.article_id);
			o.put("create_time", JsonUtil.getTime(art.create_time));
			o.put("title", art.title);
			o.put("description", art.description);
			o.put("view_type", art.view_type);
			o.put("cate", art.cate);
			o.put("url", BaseAttribute.article_url+art.article_id);
			//o.put("url","http://pet.zaiziha.com/article/detail.do?article_id="+art.article_id);
			JSONArray images = new JSONArray();
			if(BaseAttribute.view_type.grid.toString().equals(art.view_type)){
				if(!StringUtil.isEmpty(art.image3)){images.add(art.image3);}
				if(!StringUtil.isEmpty(art.image1)){images.add(art.image1);}
				if(!StringUtil.isEmpty(art.image2)){images.add(art.image2);}
			}else if(BaseAttribute.view_type.small.toString().equals(art.view_type)){
				if(!StringUtil.isEmpty(art.image1)){images.add(art.image1);}
			}if(BaseAttribute.view_type.large.toString().equals(art.view_type)){
				if(!StringUtil.isEmpty(art.image1)){images.add(art.image1);}
			}
		    o.put("images", images);
		    array.add(o);
		}
		return array;
	}
	
	
	public static JSONObject missingToJson(PetMissing petMissing){
		JSONObject o = new JSONObject();
		o.put("miss_id", petMissing.miss_id);
        o.put("age", petMissing.age);
        o.put("breed", petMissing.breed);
        o.put("create_time",JsonUtil.getTime(petMissing.create_time));
        o.put("image", petMissing.ico_path);
        o.put("sex", petMissing.sex);
        o.put("breed_name", ConstantUtil.getInstance().getName(petMissing.breed));
        o.put("city", petMissing.city);
        o.put("phone", petMissing.phone);
        o.put("pet_cate", petMissing.pet_cate);
        o.put("state", petMissing.state);
        o.put("description", petMissing.description);
        if(null!=petMissing){
        	JSONArray array = new JSONArray();
        	for(Image image:petMissing.list){
        		array.add(image.src);
        	}
        	o.put("images", array);
        }
        return o;
	}
	public static JSONArray missingToJsonArray(List<PetMissing> list){
		JSONArray array = new JSONArray();
		for(PetMissing pm:list){
			array.add(missingToJson(pm));
		}
		return array;
	}
	
	
	public static JSONObject adoptToJson(PetAdopt adopt,boolean is_apply,Integer itemCount){
		JSONObject data = new JSONObject();
		data.put("is_apply", is_apply?"1":0);		
		data.put("area", adopt.area);
		data.put("state",adopt.state);
		data.put("create_time", JsonUtil.getTime(adopt.create_time));
		data.put("breed", adopt.breed);
		data.put("breed_name", ConstantUtil.getInstance().getName(adopt.breed));
		data.put("city", adopt.city);
		data.put("phone", adopt.phone);
		data.put("is_birth", adopt.is_birth);
		data.put("is_injection", adopt.is_injection);
		data.put("age", adopt.age);
		data.put("item_count", itemCount);
		data.put("image", adopt.ico_path);
		data.put("adopt_id", adopt.adopt_id);
        data.put("description", adopt.description);
        if(null!=adopt.list){
        	JSONArray array = new JSONArray();
            for(Image image:adopt.list){
                array.add(image.src);        	
            }
            data.put("images", array);
        }
        return data;
	}
	public static JSONObject adoptToJson(PetAdopt adopt){
		JSONObject data = new JSONObject();
		data.put("area", adopt.area);
		data.put("state",adopt.state);
		data.put("create_time", JsonUtil.getTime(adopt.create_time));
		data.put("breed", adopt.breed);
		data.put("breed_name", ConstantUtil.getInstance().getName(adopt.breed));
		data.put("city", adopt.city);
		data.put("phone", adopt.phone);
		data.put("is_birth", adopt.is_birth);
		data.put("is_injection", adopt.is_injection);
		data.put("age", adopt.age);
		data.put("image", adopt.ico_path);
		data.put("adopt_id", adopt.adopt_id);
        data.put("description", adopt.description);
		
        if(null!=adopt.list){
        	JSONArray array = new JSONArray();
            for(Image image:adopt.list){
                array.add(image.src);        	
            }
            data.put("images", array);
        }
        
        return data;
	}
	public static JSONArray adoptToJsonArray(List<PetAdopt> list){
		JSONArray array = new JSONArray();
		for(PetAdopt adopt:list){
			array.add(adoptToJson(adopt));
		}
		return array;
	}
	
}